package com.lujieni.springbootmybatis.controller.admin;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.lujieni.springbootmybatis.aop.TenantIgnore;
import com.lujieni.springbootmybatis.dao.PersonDao;
import com.lujieni.springbootmybatis.dao.StudentDao;
import com.lujieni.springbootmybatis.po.PersonDO;
import com.lujieni.springbootmybatis.po.StudentDO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@Slf4j
public class TransactionController {

    private final PersonDao personDao;

    private final StudentDao studentDao;

    private final TransactionTemplate transactionTemplate;

    /**
     * 1.编程式事务中可以调用本类的private声明的方法,事务同样有效
     * 2.execute可以拿到返回的值
     */
    @GetMapping("/transaction")
    @TenantIgnore
    public void transaction(){
        StudentDO studentDO = transactionTemplate.execute(status -> {
            show1();
            return show2();
        });
        log.info("studentDO:{}", JSONUtil.toJsonStr(studentDO));
    }

    private PersonDO show1(){
        PersonDO personDO = new PersonDO();
        personDO.setMyName("马虎恶魔号");
        personDao.insert(personDO);
        return personDO;
    }

    private StudentDO show2(){
        StudentDO studentDO = new StudentDO();
        studentDO.setName("马虎恶魔号");
        studentDao.insert(studentDO);
        return studentDO;
    }


}
